//
//  SL.swift
//  0319iOSweiboDemo
//
//  Created by Tang on 16/3/30.
//  Copyright © 2016年 大天朝. All rights reserved.
//

import UIKit

import SVProgressHUD

class SLComposeViewController: UIViewController {
    
   override func viewDidLoad() {
        view.backgroundColor = UIColor.whiteColor()
        
        setupNavigationBar()
    
        prepareUI()
    
        //监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    deinit {
       NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //通知第一响应者
        textView.becomeFirstResponder()
    }
    /*
        name = UIKeyboardWillChangeFrameNotification; userInfo {  UIKeyboardAnimationCurveUserInfoKey = 7;    UIKeyboardAnimationDurationUserInfoKey = "0.25";    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";   UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";   UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";    UIKeyboardIsLocalUserInfoKey = 1;
    */
    //MARK: - 键盘frame将要改变
    func keyboardWillChangeFrame(notification: NSNotification) {
        //动画时间   可以不用双引号
        let duration = notification.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as! NSTimeInterval
        
        //目标frame
        let frame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue ?? CGRectZero
        
        //计算toolBar底部的间距
        let margin = -(UIScreen.height - frame.origin.y)
        
        //更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(margin)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    //添加左右导航栏按钮
    private func setupNavigationBar() {
        //左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        //右边边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        //发送按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
    }
    private func prepareUI() {
        setupTitleView()
        setupTextView()
        setupToolBar()
        
        setupLengthTip()
    }
    
    //设置长度提示label
    private func setupLengthTip() {
        view.addSubview(statuLengthTipLabel)
        
        //约束
        statuLengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(view).offset(-5)
            make.bottom.equalTo(toolBar.snp_top).offset(-5)
        }
    }
    
    //设置textView
    private func setupTextView() {
        //添加控件
        view.addSubview(textView)
        //让UIScrollView/子类自动适配.如果有导航栏就往下移64  默认是true
        /*
            automaticallyAdjustsScrollViewInsets:起效是有前提的
                1.UIScrollView/子类所在的控制器是在导航控制器里面的
                2.UIScrollView/需要是控制器的View(UITableView),或者UIScrollView/子类是控制器view的第一个view,UIScrollView/子类是控制器的第一个子view的第一个子view
        */
        self.automaticallyAdjustsScrollViewInsets = true
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    @objc private func picture() {
        SLPrint(msg: "图片")
    }
    @objc private func trend() {
        SLPrint(msg: "#")
    }
    @objc private func mention() {
        SLPrint(msg: "@")
    }
    @objc private func emoticon() {
//        SLPrint(msg: "表情")
         // 切换键盘, 当键盘显示的时候,设置textView.inputView是不会立马切换键盘的,系统在弹出键盘那一刻,来判断如果 textView.inputView == nil,就弹出系统的键盘,如果textView.inputView != nil,就弹textView.inputView作为键盘
        textView.resignFirstResponder()
        //设置键盘
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
      
        // 在将键盘弹出来,延迟0.25秒弹出键盘
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
    }
    @objc private func add() {
        SLPrint(msg: "加号")
    }
    
    private func setupToolBar() {
        //添加
        view.addSubview(toolBar)
        
        //toolBar约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        // 每个item对应的图片名称
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_add_background", "action": "add"]]
                         
        //创建空数组
        toolBar.items = [UIBarButtonItem]()
        var index = 0
        for dict in itemSettings {
            let imageName = dict["imageName"]!
            //获取点击事件
            let action = dict["action"]
            //Selector: 可以传入字符串.但是不能传入变量
            let item = UIBarButtonItem(imageName: imageName, targer: self, action: Selector(action!))
           
            toolBar.items?.append(item)
        
            let button = item.customView
            button?.tag = index
            index++
            
            //按钮后面添加弹簧
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //移除最后一个弹簧
        toolBar.items?.removeLast()
    }
    //导航栏标题
    private func setupTitleView() {
        let prefix = "发微博"
        if let name = SLUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            let text = prefix + "\n" + name
            let label = UILabel()
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(13)
            label.textAlignment = NSTextAlignment.Center
            label.numberOfLines = 0
            //设置属性文本
            let attr = NSMutableAttributedString(string: text)
            let nameRange = (text as NSString).rangeOfString(name)
            //给名称添加属性
//            attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            attr.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)], range: nameRange)
            label.attributedText = attr
            label.sizeToFit()
            
            navigationItem.titleView = label
        } else {
            navigationItem.title = prefix //没有名称
        }
    }
    
    //MARK: - 按钮的点击事件
    ///取消
    @objc private func dismiss() {
        SVProgressHUD.dismiss()
        //辞去第一响应者
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    ///发送微博
    @objc private func send() {
        //获取到输入的内容
        let status = textView.emoticonText()
        
        //判断是否超出长度
        if SLComposeVCStatusMaxLength - status.characters.count < 0 {
           SVProgressHUD.showErrorWithStatus("微博内容超出最大长度")
            return
        }
            
        // 发微博
        SVProgressHUD.showWithStatus("正在发布微博...", maskType: SVProgressHUDMaskType.Black)
        
        SLStatusViewModel.sharedInstance.sendStatus(status) { (error) -> () in
            if error != nil {
                SLPrint(msg: "发布微博失败: \(error)")
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            //发送微博成功，延迟关闭
        SVProgressHUD.showSuccessWithStatus("发布微博成功")
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.dismiss()
        })
            
    }
    
}

    //MARK: - 懒加载
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    /*
        iOS输入控件:
            1.UITextField
                1.只能显示一行
                2.有占位文本
                3.继承UIControl.不能滚动
            2.UITextView
                1.可以显示多行
                2.没有占位文本
                3.继承UIScrollView.能滚动
    */
    private lazy var textView: SLPlaceholderTextView = {
        let textView = SLPlaceholderTextView()
        textView.font = UIFont.systemFontOfSize(15)
        textView.textColor = UIColor.blackColor()
        textView.backgroundColor = UIColor(white: 0.8, alpha: 1)
        textView.alwaysBounceVertical = true //设置tabbleView有回弹效果
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag //拖拽键盘下去
        textView.delegate = self
        textView.placeholder = "分享新鲜事......"
        
        return textView
    }()
    
    //表情键盘
    private lazy var emoticonKeyboard: SLEmoticonKeyboard = {
        let keyboard = SLEmoticonKeyboard()
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    //长度提示的label
    private lazy var statuLengthTipLabel: UILabel = {
       let label = UILabel()
        label.font = UIFont.systemFontOfSize(11)
        label.textColor = UIColor.lightGrayColor()
        label.text = String(SLComposeVCStatusMaxLength)
        
        return label
    }()
}
//MARK: - 扩展
extension SLComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //有文字就可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        //获取文字的长度
        let length = textView.emoticonText().characters.count
        let left = SLComposeVCStatusMaxLength - length
        statuLengthTipLabel.text = String(left)
        
        //设置颜色
        statuLengthTipLabel.textColor = left < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}
